package es.udc.emarketapp.emarket.model.orderLine.dao;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.sql.GeneralOperations;
import es.udc.emarketapp.emarket.model.orderLine.vo.OrderLineVO;


// An implementation of <code>SQLOrderDAO</code> for databases providing
// counter columns with JDBC 3 drivers.
 

public class MySQLOrderLineDAO extends AbstractSQLOrderLineDAO {

    public OrderLineVO create(Connection connection, OrderLineVO orderLineVO)
        throws InternalErrorException {
        
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
    
        try {
                
            // Create "preparedStatement". 
            String queryString = "INSERT INTO linea_pedido" 
            	+ "(n_linea, n_pedido, n_compra, id_prod, uds, valor, peso) "
            	+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
        
            preparedStatement = connection.prepareStatement(queryString,
                Statement.RETURN_GENERATED_KEYS);    
            
            // Fill "preparedStatement". 
            int i = 1;
            preparedStatement.setLong(i++, orderLineVO.getnLinea());
            preparedStatement.setLong(i++, orderLineVO.getnPedido());
            preparedStatement.setLong(i++, orderLineVO.getnCompra());
            preparedStatement.setLong(i++, orderLineVO.getIdProd());
            preparedStatement.setLong(i++, orderLineVO.getUds());
            preparedStatement.setDouble(i++, orderLineVO.getValor());
            preparedStatement.setDouble(i++, orderLineVO.getPeso());
          
                        
            // Execute query.
            int insertedRows = preparedStatement.executeUpdate();
        
            if (insertedRows == 0) {
                throw new SQLException("No se pudo insertar la fila a la tabla" +
                    " 'Linea_pedido'");
            }

            if (insertedRows > 1) {
                throw new SQLException("Fila duplicada en la tabla 'Linea_pedido'");
            }
                  
            // Return the value object. 
            return new OrderLineVO(orderLineVO.getnLinea(), orderLineVO.getnPedido(),
            		orderLineVO.getnCompra(), orderLineVO.getIdProd(), 
            		orderLineVO.getUds(), orderLineVO.getValor(),
            		orderLineVO.getPeso());
        
        } catch (SQLException e) {
            throw new InternalErrorException(e);
        } finally {
            GeneralOperations.closeStatement(preparedStatement);
        }
        
    }


}